﻿using System;
using System.Net;
using System.Text.RegularExpressions;

using SWE4.Data.EmbeddedSensorCloud.DTO.Response;
using EmbeddedSensorCloud.HTTP;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public class GetInvoiceReportCommand : ICommand
    {
        #region Fields

        IInvoiceDAO _InvoiceDao;
        IPdfService _PdfService;

        #endregion

        #region Constructor

        public GetInvoiceReportCommand(IInvoiceDAO invoiceDao, IPdfService pdfService)
        {
            this._InvoiceDao = invoiceDao;
            this._PdfService = pdfService;
        }

        #endregion

        #region ICommand

        public bool CanExecute(Request param)
        {
            return (param.Method.ToUpperInvariant() == "GET" &&
                    Regex.IsMatch(param.Url, @"^/api/invoice/[0-9]+/report$", RegexOptions.IgnoreCase));
        }

        public ResponseEntity Execute(Request param)
        {
            uint id;
            string[] urlParts = param.Url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (urlParts.Length != 4 || !uint.TryParse(urlParts[2], out id) || urlParts[3].ToLowerInvariant() != "report")
            { throw new BadRequestException(); }

            InvoiceResponseModel model = this._InvoiceDao.Read(id);
            return new ResponseEntity(this._PdfService.CreatePdf(model), HttpStatusCode.OK, "application/pdf");
        }

        #endregion
    }
}
